// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise');
const TcbRouter = require('tcb-router');
cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  app.use(async (ctx, next) => {
    ctx.data = {}
    ctx.wxContext = cloud.getWXContext()
    await next()
  })
  app.router('getPhone',async (ctx,next) => {
    const res = await cloud.geoneEndata({
      list: [event.cloudID], // 假设 event.openData.list 是一个 CloudID 字符串列表
    })
	ctx.body = res
    if(typeof(res.list[0].errCode)!='undefined'){
      ctx.data.errMsg = res.list[0].errMsg
      ctx.data.errCode = res.list[0].errCode
      ctx.body = ctx.data
    }else{  
      ctx.data.errCode = 200
      ctx.data.errMsg = '获取成功！'
      ctx.data.phone = res.list[0].data.phoneNumber
      ctx.body = ctx.data
    }
  })
  app.router('getMiniCode', async (ctx, next) => {
    ctx.body = await updateIds(ctx)
    // await db.collection('user').add({data:{}})
    return
    let fileID = await getWXACode(ctx, event)
    if (!fileID) {
      ctx.data.errMsg = '获取失败！';
      ctx.data.errCode = 400
      ctx.body = ctx.data
    }
    let data = Object();
    data.miniCode = fileID;
    let res_up = await db.collection('user').where({ _openid: ctx.wxContext.OPENID }).update({ data: data })
    if (typeof (res_up.errMsg) != 'undefined') {
      if (res_up.errMsg == 'collection.update:ok') {
        ctx.data.errCode = 200
        ctx.data.errMsg = '登录成功！'
        ctx.body = ctx.data
      } else {
        ctx.data.errCode = 400
        ctx.data.errMsg = '登录失败,请重试！'
        ctx.body = ctx.data
      }
    } else {
      ctx.data.errCode = 400
      ctx.data.errMsg = '登录失败,请重试！'
      ctx.body = ctx.data
    }
  })
  // 更新用户信息
  app.router('updateUserInfo', async (ctx, next) => {
    try {
      let has = await db.collection('user').where({ _openid: ctx.wxContext.OPENID }).get();
      if (has.data.length > 0) {
        let data = Object()
        data.avatarUrl = event.userInfo.avatarUrl
        data.nickName = event.userInfo.nickName
        let res_up = await db.collection('user').where({ _openid: ctx.wxContext.OPENID }).update({ data: data })
        if (typeof (res_up.errMsg) != 'undefined') {
          if (res_up.errMsg == 'collection.update:ok') {
            ctx.data.errCode = 200
            ctx.data.errMsg = '登录成功！'
            ctx.body = ctx.data
          } else {
            ctx.data.errCode = 400
            ctx.data.errMsg = '登录失败,请重试！'
            ctx.body = ctx.data
          }
        } else {
          ctx.data.errCode = 400
          ctx.data.errMsg = '登录失败,请重试！'
          ctx.body = ctx.data
        }
      } else {
        let data = event.userInfo
        data._openid = ctx.wxContext.OPENID
        data.miniCode = '';
        ctx.name = 'user';
        let resId = await updateIds(ctx)
        if (resId.errCode == 400) {
          ctx.data.errCode = 400
          ctx.data.errMsg = '登录失败,请重试！'
          ctx.body = ctx.data
        }
        data.uid = resId._id
        let resAdd = await db.collection('user').add({ data:data });
        if (typeof (resAdd._id) != 'undefined') {
          ctx.data.errCode = 200
          ctx.data.errMsg = '登录成功！'
          ctx.data.userInfo = data
          ctx.body = ctx.data
        } else {
          ctx.data.errCode = 400
          ctx.data.errMsg = '登录失败,请重试！'
          ctx.body = ctx.data
        }

      }
    } catch (e) {
      ctx.data.errCode = 400
      ctx.data.errMsg = '登录失败,请重试！'
      ctx.body = ctx.data
    }
  })
  // 登录获取openid,sessionKey
  app.router('login', async (ctx, next) => {
    try {
      let data = await getSession(ctx, event);
      if (typeof (data.openid) != 'undefined') {
        ctx.data.data = data;
        ctx.data.errCode = 200
        ctx.data.errMsg = '操作成功！'
      } else {
        ctx.data = data
      }
    } catch (err) {
      ctx.data.errCode = 400
      ctx.data.errMsg = '请求失败'
    }
    await next(); // 执行下一中间件
  }, async (ctx, next) => {
    // 查询用户信息
    let res_user = await db.collection('user').where({_openid:ctx.wxContext.OPENID}).get()
    if(res_user.data.length){
      ctx.data.data.userInfo = res_user.data[0]
    }
    await next(); // 执行下一中间件
    },async (ctx, next) => {

      await next(); // 执行下一中间件
    },
    async (ctx) => {
    ctx.body = ctx.data
  })

  return app.serve();
}

// 获取小程序二维码
async function getWXACode(ctx, event) {

  // 此处将获取永久有效的小程序码，并将其保存在云文件存储中，最后返回云文件 ID 给前端使用
  const wxacodeResult = await cloud.openapi.wxacode.getUnlimited({
    scene: 'uid=1',
    page: 'pages/index/index',
    lineColor: { r: 198, g: 41, b: 38 },
    isHyaline: false
  })
  const fileExtensionMatches = wxacodeResult.contentType.match(/\/([^\/]+)/)
  const fileExtension = (fileExtensionMatches && fileExtensionMatches[1]) || 'jpg'
  const uploadResult = await cloud.uploadFile({
    // 云文件路径，此处为演示采用一个固定名称
    cloudPath: `wxacode_${ctx.wxContext.OPENID}.${fileExtension}`,
    // 要上传的文件内容可直接传入图片 Buffer
    fileContent: wxacodeResult.buffer,
  })
  if (!uploadResult.fileID) {
    return false;
  }
  return uploadResult.fileID
}
// 获取session
async function getSession(ctx, event) {
  return rp(`https://api.weixin.qq.com/sns/jscode2session?appid=${ctx.wxContext.APPID}&secret=${ctx.secret}&jsCode=${event.code}&grantType=authorizationCode`)
    .then(function (res) {
      let data = JSON.parse(res)
      return data;
    })
    .catch(function (err) {
      return err;
    });

  // var options = {
  //   method: 'POST',
  //   uri: 'http://api.posttestserver.com/post',
  //   body: {
  //     some: 'payload'
  //   },
  //   json: true 
  // };
}
// token存储
async function getAccessToken(ctx) {
  let has = await db.collection('commonInfo').where({ 'key': 'accessToken' }).get();
  if (has.data.length == 0) {
    let accessToken = await curlAccessToken(ctx)
    if (typeof (accessToken.errcode) != 'undefined') {
      return accessToken;
    }
    let data = {};
    data.key = 'accessToken';
    data.value = accessToken.accessToken;
    data.expireTime = new Date().getTime() + 7000 * 1000;
    await db.collection('commonInfo').add({ data: data })
    return accessToken;
  } else {
    if (has.data[0].expireTime < new Date().getTime()) {
      let accessToken = await curlAccessToken(ctx)
      if (typeof (accessToken.errcode) != 'undefined') {
        return accessToken;
      }
      let data = {};
      data.value = accessToken.accessToken;
      data.expireTime = new Date().getTime() + 7000 * 1000;
      await db.collection('commonInfo').where({
        key: 'accessToken'
      }).update({ data: data })
      return accessToken;
    }
    return { 'accessToken': has.data[0].value };
  }
  // errMsg: "collection.add:ok"
  // Id: "1acf1de95e4628b50f7ce7fc775baa8e"
  //  return await db.collection('commonInfo').add({data:{'accessToken':'uyiduSYDUFUDAISOFKAJSFDS','expireTime':1234567}})
}
// token接口
async function curlAccessToken(ctx) {
  return rp(`https://api.weixin.qq.com/cgi-bin/token?grantType=clientCredential&appid=${ctx.wxContext.APPID}&secret=${ctx.secret}`)
    .then(function (res) {
      let data = JSON.parse(res)
      return data;
    })
    .catch(function (err) {
      return err;
    });
}
// 更新ids
async function updateIds(ctx) {
  const _ = db.command
  let has = await db.collection('ids').where({ name: ctx.name }).get()
  if (has.data.length == 0) {
    let resAdd = await db.collection('ids').add({ data: { name: ctx.name, id: 1 } });
    if (typeof (resAdd._id) != 'undefined') {
      return await { errCode: 200, id: 1 }
    } else {
      return { errCode: 400 }
    }
  } else {
    let res_up = await db.collection('ids').where({ name: ctx.name }).update({ data: { id: _.inc(1) } })
    if (res_up.stats.updated == 1) {
      return { errCode: 200, id: has.data[0]._id + 1 }
    } else {
      return { errCode: 400 }
    }
  }
}